<?php
/**
 * 用户组类
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2018/7/20
 * Time: 15:45
 */
namespace app\admin\controller;

class Group extends Base{
    /**
     * 用户组列表
     * search 参数 $this->params:表单参数 input精确查找 时间查找 select状态查找
     * @return \think\response\View
     */
    public function groupList(){
        $search = search($this->params,['group_name']);
        $where  = $search['where'] ? $search['where'].' and ' : '';
        $where .= 'id > '.\Param::GROUP_ADMIN.' and status in ('.\Param::STATUS_ON.', '.\Param::STATUS_OFF.')';
        $list   = $this->getList($this->auth_group, $where);
        foreach ($list as $k=>$v) {
            $rules = $this->getColumn($this->auth_rule, ['id'=>['in',$v['auth_ids']]],'rule_name');
            $list[$k]['auth_ids'] = implode(',',$rules);
        }
        if(!$this->params) $list = infinite($list);  // 检索的话不递归
        $count = count($list);  // 统计条数
        return view('groupList',['list'=>$list,'count'=>$count,'params'=>$search['params']]);
    }

    /**
     * 操作用户组
     * @return array|\think\response\View
     */
    public function groupSave(){
        $info = !empty($this->params['id']) ? $this->getRow($this->auth_group, $this->params['id']) : [
            'group_name' => '',
            'auth_ids'   => '',
            'status'     => \Param::STATUS_ON,
            'pid'        => 0,
            'id'         => ''
        ];

        if(IS_POST){
            try{
                if (!empty($this->params['id'])) {
                    //todo 更新
                    $validate = self::validate($this->params,'Group.groupSave');  // 场景验证
                    if(true !== $validate) throw new \Exception($validate, -1);

                    $this->params['auth_ids'] = implode(',',$this->params['auth_ids']);
                    $result = compare($this->params,$info);  //参数对比, 拼接变动的参数，无改动直接返回
                    if(!$result) return _success();

                    $this->params['update_time'] = time();
                    $row = $this->auth_group->update($this->params);  // 更新用户组信息
                    if(false === $row) throw new \Exception('操作失败', -1);

                    $this->logs[] = ['修改用户组', \Param::LOG_TYPE_EDIT, "修改“ID：{$info['id']}”用户组{$result}"];
                } else {
                    //todo 添加
                    $validate = self::validate($this->params,'Group.groupAdd');  // 场景验证
                    if(true !== $validate) throw new \Exception($validate, -1);

                    $this->params['auth_ids'] = implode(',',$this->params['auth_ids']);
                    $this->params['create_time'] = time();
                    $id = $this->auth_group->insertGetId($this->params);  // 添加用户组
                    if(!$id) throw new \Exception('操作失败', -1);

                    $this->logs[] = ['新增用户组', \Param::LOG_TYPE_ADD ,"新增“ID：{$id}”用户组“{$this->params['group_name']}”"];
                }
            } catch (\Exception $e) {
                return _error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return _success();
        }

        //判断显示全部权限还是关联权限
        $where = $info['pid'] > 0
            ? ['id'=>['in',$info['auth_ids']],'status'=>\Param::STATUS_ON]
            : ['status'=>\Param::STATUS_ON];

        $list = $this->getList($this->auth_rule, $where, 'id,pid,rule_name');
        return view('groupSave',['list'=>$list,'info'=>$info]);
    }

    /**
     * 修改状态
     * @return array
     */
    public function status(){
        if(IS_POST){
            try{
                $info = $this->getRow($this->auth_group, $this->params['id']);
                if(!$info || $info['status'] == \Param::STATUS_DEL) throw new \Exception('该用户组不存在', -1);

                $row = $this->auth_group->update(['id'=>$this->params['id'],'status'=>$this->params['status']]);
                if (false === $row) throw new \Exception('操作失败', -1);

                $status = $this->params['status'] == \Param::STATUS_ON ? '已启用' : '已禁用';

                $this->logs[] = ['修改用户组', \Param::LOG_TYPE_EDIT, "修改“ID：{$info['id']}”用户组“{$info['group_name']}”状态为“{$status}”"];
            } catch(\Exception $e) {
                return _error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return _success();
        }
    }

    /**
     * 关联下级
     * @return \think\response\View
     */
    public function groupRelation(){
        $info = $this->getRow($this->auth_group, $this->params['id']);
        $where = $this->params['id'] == \Param::GROUP_ADMIN
            ? ['status'=>\Param::STATUS_ON]
            : ['id'=>['in',$info['auth_ids']],'status'=>\Param::STATUS_ON];

        $list = $this->getList($this->auth_rule, $where, 'id,pid,rule_name');  //获取权限列表
        return view('groupRelation',['list'=>$list,'info'=>$info]);
    }
}